import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-calendar',
	templateUrl: './calendar.component.html',
	styleUrls: ['./calendar.component.css'],
})
export class CalendarComponent implements OnInit {
	@Input() initCalendarFlag:any;
	private $calendarRef: any;
	private calendar: any;
	public period = '按天汇总'
	deviceInstallData: any = []; //设备安装统计数据缓存
	renderData: any = []; //日历渲染的list
	sortType: string = 'month';//统计模式
	currentYear: any;//按年统计模式:年份参数
	yearDataList: any = [];//按年统计模式:页面渲染月份数据
	calendarParam:any = {
		year:'',
		month:'',
	}//按月统计模式:接口参数
	constructor(private el: ElementRef, private jsonApiService: JsonApiService) {}
	ngOnInit() {
		System.import('script-loader!smartadmin-plugins/bower_components/fullcalendar/dist/fullcalendar.js');
	}
	ngOnChanges() {
		if(this.initCalendarFlag){
			this.calendarParam.year = common.getNowTime().split('-')[0];
			this.calendarParam.month = common.getNowTime().split('-')[1];
			System.import('script-loader!smartadmin-plugins/bower_components/fullcalendar/dist/fullcalendar.js').then(() => {
				this.initCalendarData().then(()=>{
					setTimeout(()=>{this.render();},100);
				})
			})
		}
	}
	//日历数据拉取
	initCalendarData() {
		var that = this;
		this.deviceInstallData = [];
		this.renderData = [];
		return new Promise(function(resolve, reject) {
			if(that.deviceInstallData.length < 1) {
				that.jsonApiService.http_obj('deviceRepaired/statisticsDeviceRepairedCount.html', {year:that.calendarParam.year,month:that.calendarParam.month}).subscribe((result) => {
					that.deviceInstallData = result.data;
					if(that.sortType == 'month') {
						if(that.renderData.length == 0){
							for(let item of that.deviceInstallData) {
								var temObj = {
									title: item.title,
									preTitle:item.preDate?item.preTotalCount:'',
									start: item.start,
									preDate:item.preDate?item.preDate+'维修'+item.preTotalCount+'台':'',
									description: item.array
								}
								that.renderData.push(temObj);
							}
						}
						resolve()
					}
					
				})
			}
		})
		
	}
	//日历渲染
	render() {
		if(!document.getElementById('calendar')) return;
		this.$calendarRef = $(document.getElementById('calendar'));
		this.calendar = this.$calendarRef.fullCalendar({
			lang: 'zh-cn',
			editable: false,
			draggable: false,
			selectable: false,
			selectHelper: true,
			unselectAuto: false,
			disableResizing: false,
			droppable: true,
			header: {
				left: 'title', //,today
				center: 'prev, next, today',
				right: 'month, agendaWeek, agendaDay' //month, agendaDay,
			},
			select: (start, end, allDay) => {
				var title = prompt('Event Title:');
				if(title) {
					this.calendar.fullCalendar('renderEvent', {
						title: title,
						start: start,
						end: end,
						allDay: allDay
					}, true); // 事件可“粘连”
				}
				this.calendar.fullCalendar('unselect');
			},
			events: this.renderData,
			eventRender: (event, element, icon) => {
				if(event.description != "") {
					element.find('.fc-event-title').append("<br/><span class='ultra-light'>" + event.description + "</span>");
				}
				if(event.icon != "") {
					element.find('.fc-event-title').append("<i class='air air-top-right fa " + event.icon + " '></i>");
				}
			}
		});
		$('.fc-header-right, .fc-header-center', this.$calendarRef).hide();
		$('.fc-left', this.$calendarRef).addClass('fc-header-title');
	}
	ngOnDestroy() {
//	  	this.calendar.fullCalendar('destroy')
	}

	//视图切换
	changeView(period) {
		if(period == 'month') {
			this.sortType = 'month';
			this.period = '按天汇总';
			this.calendar.fullCalendar('changeView', period);
		} else if(period == 'year') {
			this.sortType = 'year';
			this.period = '按月汇总';
			this.initYear();
			this.getYearData();
		}
	}
	//年统计数据
	getYearData() {
		this.initYearView();
		let reqdate = 'year=' + this.currentYear;
		this.jsonApiService.http('deviceRepaired/statisticsDeviceRepairedCount.html', reqdate).subscribe((result) => {
			let data = result.data;
			let list = [];
			if(data.length > 0 && result.success) {
				for(let item of data) {
					for(let lis of this.yearDataList) {
						if(item.start == lis.id) {
							lis.value = item.title;
							lis.preValue = item.preTotalCount;
							lis.preDate = item.preDate+'维修'+lis.preValue+'台';
							lis.description = this.findChildCompany(item.array);
						}
					}
				}
			} else {
				this.initYearView();
			}
		})
	}

	findChildCompany(arr) {
		let listName = [];
		for(let item of arr) {
			let index = listName.indexOf(item.parentName);
			if(index < 0) listName.push(item.parentName);
		}
		var resultArr = [];
		for(let iems of listName) {
			if(iems) {
				let itemObj = {
					name: iems,
					child: [],
					count: 0
				}
				for(let company of arr) {
					if(company.parentName == iems) {
						itemObj.child.push(company);
						itemObj.count += company.count;
					}
				}
				resultArr.push(itemObj);
			} else {
				for(let company of arr) {
					if(company.parentName == iems) {
						resultArr.push({
							name: company.companyName,
							child: [],
							count: company.count
						});
					}
				}
			}
		}
		resultArr.sort((a, b) => {
			return(b.count - a.count)
		});
		return resultArr;
	}

	//获取当前年
	initYear() {
		this.currentYear = new Date().getFullYear();
	}
	//上一年
	prevYear() {
		if(this.currentYear) {
			this.currentYear = this.currentYear - 1;
			this.getYearData();
		}
	}
	//下一年
	nextYear() {
		if(this.currentYear) {
			this.currentYear = this.currentYear + 1;
			this.getYearData();
		}
	}
	//今年
	CurrentYear(){
		this.initYear();
		this.getYearData();
	}
	//下个月
	next() {
		$('.fc-next-button', this.el.nativeElement).click();
		let currentMonth = common.getTimeMmss(this.calendar.fullCalendar('getDate')._d);//获取当前月
		this.calendarParam.year = currentMonth.split('-')[0];
		this.calendarParam.month = currentMonth.split('-')[1];
		this.initCalendarData().then(()=>{
			this.calendar.fullCalendar('destroy');//销毁对象
			this.render();//重新生成日历
			this.calendar.fullCalendar('gotoDate',this.calendarParam.year+'-'+this.calendarParam.month);//跳转指定日期
		})
	}
	//上个月
	prev() {
		$('.fc-prev-button', this.el.nativeElement).click();
		let currentMonth = common.getTimeMmss(this.calendar.fullCalendar('getDate')._d);//获取当前月
		this.calendarParam.year = currentMonth.split('-')[0];
		this.calendarParam.month = currentMonth.split('-')[1];
		this.initCalendarData().then(()=>{
			this.calendar.fullCalendar('destroy');//销毁对象
			this.render();//重新生成日历
			this.calendar.fullCalendar('gotoDate',this.calendarParam.year+'-'+this.calendarParam.month);//跳转指定日期
		})
	}
	//今天
	today() {
		$('.fc-today-button', this.el.nativeElement).click();
		this.calendarParam.year = common.getNowTime().split('-')[0];
		this.calendarParam.month = common.getNowTime().split('-')[1];
		this.initCalendarData().then(()=>{
			this.calendar.fullCalendar('destroy');//销毁对象
			this.render();//重新生成日历
			this.calendar.fullCalendar('gotoDate',this.calendarParam.year+'-'+this.calendarParam.month);//跳转指定日期
		})
	}
	initYearView() {
		this.yearDataList = [{
			id: '01',
			label: '一月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}, {
			id: '02',
			label: '二月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}, {
			id: '03',
			label: '三月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}, {
			id: '04',
			label: '四月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}, {
			id: '05',
			label: '五月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}, {
			id: '06',
			label: '六月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}, {
			id: '07',
			label: '七月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}, {
			id: '08',
			label: '八月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}, {
			id: '09',
			label: '九月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}, {
			id: '10',
			label: '十月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}, {
			id: '11',
			label: '十一月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}, {
			id: '12',
			label: '十二月',
			value: '',
			preValue:'',
			preDate:'',
			description: ''
		}]
	}
}